<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>发布实验</title>
    <style>
        .el-table .warning-row {
            background: oldlace;
        }

        .el-table .success-row {
            background: #f0f9eb;
        }
    </style>

</head>
<body>
<div id="app">

    <!--搜索表单-->
    <el-form :inline="true" ref="reportSearchForm" :model="reportSearch" class="demo-form-inline"
             @submit.native.prevent>

        <el-form-item label="实验名" prop="reportName">
            <el-input v-model="reportSearch.reportName" placeholder="实验名"></el-input>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="searchReport" native-type="submit">查询实验</el-button>
            <el-button type="warning" @click="resetSearchReport">重置</el-button>
        </el-form-item>

    </el-form>

    <!--按钮-->
    <el-row>
        <el-button type="danger" plain @click="deleteReports">-批量删除</el-button>
        <el-button type="primary" plain @click="dialogVisibleAdd = true">+新增实验</el-button>
    </el-row>

    <!--  发布实验弹窗  -->
    <el-dialog
            title="发布实验"
            :visible.sync="dialogVisibleAdd"
            width="40%"
            @close="report={};reportQuestions={questions: [{question: ''}]}">
        <el-form ref="addReportForm" :model="report" label-width="80px">

            <el-form-item label="实验名" prop="reportName"
                          :rules="[{ required: true, message: '请输入实验名', trigger: 'blur' }]">
                <el-input  v-model="report.reportName" placeholder="请输入实验名"
                           maxlength="20" show-word-limit></el-input>
            </el-form-item>

            <div class="block">
                <span class="demonstration">选择截止时间</span>
                <el-date-picker
                        v-model="report.reportDate"
                        align="center"
                        type="date"
                        placeholder="选择日期"
                        :picker-options="pickerOptions">
                </el-date-picker>
            </div>

            <br>

            <el-form-item
                    v-for="(question, index) in reportQuestions.questions"
                    :label="'问题' + (index+1)"
                    :key="question.key"
                    :prop="'questions.' + index + '.question'"
            ><el-input v-model="question.question"></el-input>
                <el-button @click.prevent="removeQuestion(question)">删除</el-button>
            </el-form-item>

            <div style="text-align: center;">
                <el-button type="success" @click="addQuestion">新增问题</el-button>
                <el-button type="danger" @click.prevent="reportQuestions={questions: [{question: ''}]}">重置所有问题</el-button>
            </div>

            <br>
            <el-divider></el-divider>
            <el-form-item>
                <el-button type="primary" @click="addReport();dialogVisibleAdd = false">提交</el-button>
                <el-button type="info" @click="addReport()">保存并继续添加</el-button>
                <el-button @click="dialogVisibleAdd = false">取消</el-button>
            </el-form-item>
        </el-form>

    </el-dialog>

    <!--  修改实验弹窗  -->
    <el-dialog
            title="修改实验"
            :visible.sync="dialogVisibleUpdate"
            width="40%"
            @close="report={};reportQuestions={questions: [{question: ''}]}">

        <el-form ref="updateReportForm" :model="report" label-width="80px">

            <el-form-item label="实验名" prop="reportName"
                          :rules="[{ required: true, message: '请输入实验名', trigger: 'blur' }]">
                <el-input  v-model="report.reportName" placeholder="请输入实验名"
                           maxlength="20" show-word-limit></el-input>
            </el-form-item>

            <div class="block">
                <span class="demonstration">选择截止时间</span>
                <el-date-picker
                        v-model="report.reportDate"
                        align="center"
                        type="date"
                        placeholder="选择日期"
                        :picker-options="pickerOptions">
                </el-date-picker>
            </div>

            <br>

            <el-form-item
                    v-for="(question, index) in reportQuestions.questions"
                    :label="'问题' + (index+1)"
                    :key="question.key"
                    :prop="'questions.' + index + '.question'"
            ><el-input v-model="question.question"></el-input>
                <el-button @click.prevent="removeQuestion(question)">删除</el-button>
            </el-form-item>

            <div style="text-align: center;">
                <el-button type="success" @click="addQuestion">新增问题</el-button>
                <el-button type="danger" @click.prevent="reportQuestions={questions: [{question: ''}]}">重置所有问题</el-button>
            </div>

            <br>
            <el-form-item>
                <el-button type="primary" @click="updateReport">提交</el-button>
                <el-button @click="dialogVisibleUpdate = false;">取消</el-button>
            </el-form-item>
        </el-form>

    </el-dialog>

    <!--  查看详细弹窗  -->
    <el-dialog
            title="查看详细"
            :visible.sync="dialogVisibleShow"
            width="40%"
            @close="report={};reportQuestions={questions: [{question: ''}]}">
        <el-form ref="showReportForm" :model="report" label-width="80px">
                <el-form-item label="实验名:">
                    <div class="sub-title;">{{ report.reportName }}</div>
                </el-form-item>
            <el-form-item v-for="(item,index) in reportQuestions.questions" v-if="item.question">
                问题{{ index }}：{{ item.question }}
                <el-divider></el-divider>
            </el-form-item>
            <br>
        </el-form>
    </el-dialog>
    <br>
    <!--表格-->
    <template>
        <el-table
                :data="tableData"
                style="width: 100%"
                :row-class-name="tableRowClassName"
                border
                @selection-change="handleSelectionChange"
        >
            <el-table-column
                    type="selection"
                    width="55"
                    align="center">
            </el-table-column>

            <el-table-column
                    prop="reportName"
                    label="实验名"
                    align="center"
                    sortable
            >
            </el-table-column>

            <el-table-column
                    label="问题"
                    align="center"
            >
                <template slot-scope="scope">
                    <el-button type="info" @click="showDetail(scope.row)">查看</el-button>
                </template>
            </el-table-column>

            <el-table-column
                    prop="reportDate"
                    label="截止时间"
                    align="center"
                    sortable
            >
            </el-table-column>

            <el-table-column
                    align="center"
                    label="操作">

                <template slot-scope="scope">
                    <el-button type="primary" @click="selectReportById(scope.row)">修改</el-button>
                    <el-button type="danger" @click="deleteReport(scope.row)">删除</el-button>
                </template>

            </el-table-column>

        </el-table>
        <!--分页工具条-->
        <el-pagination
                class="pageList"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalCount"
                :current-page.sync="currentPage"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
        >
        </el-pagination>
    </template>
    <br>
</div>

<link rel="stylesheet" href="../../plugins/element-ui/lib/theme-chalk/index.css">
<script src="../../plugins/vue/vue.js"></script>
<script src="../../plugins/element-ui/lib/index.js"></script>
<script src="../../plugins/axios/axios.min.js"></script>

<script>
    //关闭控制台vue的提示
    Vue.config.productionTip = false;
    new Vue({
        el: "#app",
        //页面使用到的数据
        data() {
            return {
                //使用搜索的标志(默认关闭,在搜索一次后开启)
                searchFlag: 0,
                // 每页显示的条数
                pageSize: 10,
                // 总记录数
                totalCount: 0,
                // 当前页码
                currentPage: 1,
                // 添加数据对话框是否展示的标记
                dialogVisibleAdd: false,
                //批量添加实验
                dialogVisibleShow: false,
                //修改数据对话框
                dialogVisibleUpdate: false,
                //页面信息
                userInfo: {},
                // 实验模型数据
                report: {
                    id: '',
                    reportName: '',
                    reportQuestion: '',
                    reportClass: '',
                    reportDate: ''
                },
                //问题列表
                reportQuestions :{
                    questions: [{
                        question: ''
                    }]
                },
                //实验搜索数据模型
                reportSearch: {
                    reportName: '',
                    reportClass: ''
                },
                // 被选中的id数组
                selectedIds: [],
                // 复选框选中数据集合
                multipleSelection: [],
                // 表格数据(静态数据)
                tableData: [
                    {
                        id: '1',
                        reportName: '1',
                        reportQuestion: '1',
                        reportDate: '1'
                    },
                    {
                        id: '1',
                        reportName: '1',
                        reportQuestion: '1',
                        reportDate: '1'
                    }
                ],
                //日期选择器
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() < Date.now();
                    },
                    shortcuts: [{
                        text: '3天后',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() + 3600 * 1000 * 24 * 3);
                            picker.$emit('pick', date);
                        }
                    }, {
                        text: '7天后',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', date);
                        }
                    }, {
                        text: '15天后',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() + 3600 * 1000 * 24 * 15);
                            picker.$emit('pick', date);
                        }
                    }, {
                        text: '30天后',
                        onClick(picker) {
                            const date = new Date();
                            date.setTime(date.getTime() + 3600 * 1000 * 24 * 30);
                            picker.$emit('pick', date);
                        }
                    }]
                },
            }
        },
        mounted() {
            //保存用户数据到当前页面
            const userInfo = window.localStorage.getItem('userInfo')
            if (userInfo) {
                this.userInfo = JSON.parse(userInfo)
            }
            this.selectAll();
        },
        methods: {
            // 查询所有实验数据并分页
            selectAll() {
                //如果使用过搜索功能，就将表格改成搜索的内容
                if (this.searchFlag === 1) {
                    this.searchReport();
                } else {
                    axios({
                        method: "get",
                        url: "/report/selectAllTch",
                        params: {
                            currentPage: this.currentPage,
                            pageSize: this.pageSize,
                            teacherClass: this.userInfo.teacherClass
                        },
                    }).then(res => {
                        this.tableData = res.data.tableData || [];
                        this.totalCount = res.data.totalCount;
                    }).catch(() => {
                        this.$message({
                            message: '查询失败!已为您加载静态数据',
                            type: 'warning'
                        });
                    })
                }
            },

            //查询单个实验信息，回显信息到表单
            selectReportById(val) {
                //弹窗修改信息
                this.report = val;
                this.reportQuestions = {
                    questions: []
                }
                //通过id来回显实验信息
                axios({
                    method: "get",
                    url: "/report/selectById/" + this.report.id
                }).then(res => {
                    this.report = res.data;
                    let q = this.report.reportQuestion.split(';')
                    q.forEach((item) => {
                        if (item !== ''){
                            let obj = {question:item}
                            this.reportQuestions.questions.push(obj)
                        }
                    })
                    this.dialogVisibleUpdate = true;
                }).catch(() => {
                    this.$message({
                        message: '数据异常！',
                        type: 'warning'
                    });
                })
            },

            //显示详细问题
            showDetail(val){
                this.report = val;
                this.reportQuestions = {
                    questions: []
                }
                //通过id来回显实验信息
                axios({
                    method: "get",
                    url: "/report/selectById/" + this.report.id
                }).then(res => {
                    this.report = res.data;
                    let q = this.report.reportQuestion.split(';')
                    q.forEach((item) => {
                        if (item !== ''){
                            let obj = {question:item}
                            this.reportQuestions.questions.push(obj)
                        }
                    })
                    this.dialogVisibleShow = true;
                }).catch(() => {
                    this.$message({
                        message: '数据异常！',
                        type: 'warning'
                    });
                })
                this.report = {}
                this.reportQuestions = {
                    questions: [{
                        question: ''
                    }]
                }
            },

            // 工具栏查询实验数据
            searchReport() {
                axios({
                    method: "post",
                    url: "/report/selectByConditionsTch",
                    data: this.reportSearch,
                    params: {
                        currentPage: this.currentPage,
                        pageSize: this.pageSize,
                        teacherClass: this.userInfo.teacherClass
                    }
                }).then(res => {
                    this.tableData = res.data.tableData || [];
                    this.totalCount = res.data.totalCount;
                    this.searchFlag = 1;//搜索成功的标志
                }).catch(() => {
                    this.$message({
                        message: '数据异常！',
                        type: 'warning'
                    })
                })
            },

            //重置查询
            resetSearchReport() {
                this.resetForm('reportSearchForm')
                this.searchFlag = 0
                this.selectAll()
            },

            //修改数据
            updateReport() {
                let val = ''
                this.reportQuestions.questions.forEach((item) => {
                    let obj = {question: item.question}
                    val += item.question + ';'
                })
                this.report.reportQuestion = val
                this.report.reportDate = this.formatDateTime(this.report.reportDate, 'yyyy-MM-dd')
                axios({
                    method: "put",
                    url: "/report/update/" + this.report.id,
                    data: this.report,
                }).then(res => {
                    if (res.data) {
                        this.$message({
                            message: '修改成功！',
                            type: 'success'
                        });
                        this.dialogVisibleUpdate = false;
                        this.selectAll();
                    } else {
                        this.$message({
                            message: '数据异常，请检查数据再提交！',
                            type: 'warning'
                        });
                    }
                })
                this.report = {}
                this.reportQuestions = {
                    questions: [{
                        question: ''
                    }]
                }
            },

            //添加实验
            addReport() {
                let val = ''
                this.reportQuestions.questions.forEach((item) => {
                    let obj = {question: item.question}
                    val += item.question + ';'
                })
                this.report.reportQuestion = val
                this.report.reportClass = this.userInfo.teacherClass
                this.report.reportDate = this.formatDateTime(this.report.reportDate, 'yyyy-MM-dd')
                // 发送ajax请求，添加数据
                axios({
                    method: "post",
                    url: "/report/save",
                    data: this.report,
                }).then(() => {
                    //添加成功
                    // 重新查询数据
                    this.selectAll();
                    // 弹出消息提示
                    this.$message({
                        message: '恭喜你，添加成功',
                        type: 'success'
                    })
                }).catch(() => {
                    this.$message({
                        message: '未填写数据，已为你关闭窗口',
                        type: 'warning'
                    })
                });
                this.report = {}
                this.reportQuestions = {
                    questions: [{
                        question: ''
                    }]
                }
            },

            //删除实验数据
            deleteReport(val) {
                this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.report = val;
                    axios({
                        method: "delete",
                        url: "/report/deleteById/" + this.report.id
                    }).then(() => {
                        this.selectAll();
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.report = {}
                        this.reportQuestions = {
                            questions: [{
                                question: ''
                            }]
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });

            },

            //批量删除实验
            deleteReports() {
                // 弹出确认提示框
                this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //用户点击确认按钮
                    for (let i = 0; i < this.multipleSelection.length; i++) {
                        let selectionElement = this.multipleSelection[i];
                        this.selectedIds[i] = selectionElement.id;
                    }
                    // 发送ajax请求，删除数据
                    axios({
                        method: "post",
                        url: "/report/deleteByIds",
                        data: this.selectedIds
                    }).then(() => {
                        // 重新查询数据
                        this.selectAll();
                        // 弹出消息提示
                        this.$message({
                            message: '恭喜你，删除成功',
                            type: 'success'
                        });
                        this.selectedIds = []
                    }).catch(() => {
                        this.$message({
                            message: '出现异常',
                            type: 'warning'
                        });
                    })
                }).catch(() => {
                    //用户点击取消按钮
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
                this.selectedIds = []
            },

            //表格颜色，偶数绿色
            tableRowClassName({row, rowIndex}) {
                if (rowIndex % 2 === 1) {
                    return 'success-row';
                }
                return '';
            },

            // 复选框选中后执行的方法，
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },

            //设置左侧每次显示多少条信息
            handleSizeChange(val) {
                // 重新设置每页显示的条数
                this.pageSize = val;
                this.selectAll();
            },

            //设置右侧跳转多少页
            handleCurrentChange(val) {
                // 重新设置当前页码
                this.currentPage = val;
                this.selectAll();
            },

            //删除表元素
            removeQuestion(item) {
                var index = this.reportQuestions.questions.indexOf(item)
                if (index !== -1) {
                    this.reportQuestions.questions.splice(index, 1)
                }
            },
            //增加表元素
            addQuestion() {
                this.reportQuestions.questions.push({
                    question: '',
                    key: Date.now()
                });
            },

            //重置表单
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },

            //格式化时间
            formatDateTime(date, format) {
                const o = {
                    'M+': date.getMonth() + 1, // 月份
                    'd+': date.getDate(), // 日
                    'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小时
                    'H+': date.getHours(), // 小时
                    'm+': date.getMinutes(), // 分
                    's+': date.getSeconds(), // 秒
                    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
                    S: date.getMilliseconds(), // 毫秒
                    a: date.getHours() < 12 ? '上午' : '下午', // 上午/下午
                    A: date.getHours() < 12 ? 'AM' : 'PM', // AM/PM
                };
                if (/(y+)/.test(format)) {
                    format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                for (let k in o) {
                    if (new RegExp('(' + k + ')').test(format)) {
                        format = format.replace(
                            RegExp.$1,
                            RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
                        );
                    }
                }
                return format;
            },
        }
    })
</script>
</body>
</html>